<!--
 * @Author: wuyuxin
 * @Date: 2022-01-08 21:42:50
 * @LastEditors: wuyuxin
 * @LastEditTime: 2022-01-09 16:49:52
 * @Description: 
-->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>

    class SnapshotSandbox{
      constructor() {
        this.proxy = window;
        this.modifyPropsMap = {}; // 记录在window上的修改
        this.active()
      }
      active() {
        this.windowSnapshot = {}
        for(const prop in window) {
          if (window.hasOwnProperty(prop)) {
            this.windowSnapshot[prop] = window[prop]
          }
        }
        Object.keys(this.modifyPropsMap).forEach(p => {
          window[p] = this.modifyPropsMap[p]
        })
      }
      inactive() {
        for(const prop in window) {
          if (window.hasOwnProperty(prop)) {
            if (this.windowSnapshot[prop] !== window[prop]) {
              this.modifyPropsMap[prop] = window[prop]
              window[prop] = this.windowSnapshot[prop]
            }
          }
        }
      }
    }

    let sandbox = new SnapshotSandbox();

    ((window) => {
      window.a = 1;
      window.b = 2;
      console.log(window.a, window.b)
      sandbox.inactive();
      console.log(window.a, window.b)
      sandbox.active()
      console.log(window.a, window.b)

    })(sandbox.proxy) // sandbox.proxy 就是window


    // 代理沙箱可以实现多应用沙箱。把不同的应用用不同的代理

  </script>
</body>
</html>
